/**
 * Simplest Telnet client
 */

import java.net.*;
import java.io.*;

class InputHandler extends Thread {
    InputStream in = null;
    public InputHandler(InputStream _in) 
    {
        in = _in;
    }

    @Override
    public void run() {
        int n;
        byte byteList[] = new byte[100]; // can be more?
        try {

            while ((n = in.read(byteList)) > 0) {
                String str = "";
                str = new String(byteList, 0, n);
                System.out.println(str);
            }
        } catch (Exception e) {
            System.err.println("InputHandler ex: " + e);
        }

        System.out.println("Connection closed.");
        System.exit(0);

        
    }
}


public class Telnet {


    /**
     * @param host  a string host name, used by new Socket
     * @param port  int port
     * @throws Exception
     */
    public static void telnetClient(String host, int port) throws Exception
    {
        Socket sock;
        InputStream in;
        OutputStream out;

        sock = new Socket(host, port);

        out = sock.getOutputStream();
        in = sock.getInputStream();
        // prepare a thread reading network input
        new InputHandler(in).start();

        InputStream stdin = System.in;
        byte byteList[] = new byte[100];
        try {
            int n;
            // String str = new String(byteList, 0, n);
            // meaning the socket connection has been closed.
            // may need non-blocking tools
            while ((n = stdin.read(byteList)) > 0) {
                // System.out.println("stdin: " + str);
                out.write(byteList, 0, n);
                if (n <= 0) {
                    System.out.println("Write 0, connection closed");
                    break;
                }
            }

        } catch (Exception e) {
            System.err.println("stdin read loop err: " + e);
            // e.printStackTrace();
        }

        sock.close();
    }


    public static void main(String arg[]) 
    {
        if (arg.length < 2) {
            System.out.println("");
            System.out.println("Usage: java Telnet [host] [port]");
            System.out.println("arglen=" + arg.length);

            return;
        }

        String host = "0.0.0.0";
        int port = 7749;

        host = arg[0];
        try {
            port = Integer.parseInt(arg[1]);
        } catch (Exception e) {
            System.err.println("parseInt(port) error: " + e);
            return;
        }

        System.out.println("Connecting to " + host + ":" + port);

        try {
            telnetClient(host, port);
        } catch (Exception e) {
            System.err.println("telnetClient err: " + e);
            e.printStackTrace();
        }


    }
}
